import React, { useState, useRef, useEffect } from 'react';
// 函数组件 - 现代React推荐的写法
function TodoItem({ todo, toggleTodo, deleteTodo, editTodo }) {
  const [isEditing, setIsEditing] = useState(false);
  const [editText, setEditText] = useState(todo.text);
  const editInputRef = useRef(null);
  
  // 编辑模式下自动聚焦输入框
  useEffect(() => {
    if (isEditing && editInputRef.current) {
      editInputRef.current.focus();
    }
  }, [isEditing]);
  
  const handleEdit = () => {
    setIsEditing(true);
  };
  
  const handleSave = () => {
    console.log('handleSave called');
    console.log('editTodo type:', typeof editTodo);
    
    if (editText.trim() !== '' && typeof editTodo === 'function') {
      console.log('Calling editTodo with:', todo.id, editText);
      editTodo(todo.id, editText);
      setIsEditing(false);
    } else {
      console.error('editTodo is not a function or text is empty');
      setIsEditing(false);
    }
  };
  
  const handleKeyDown = (e) => {
    if (e.key === 'Enter') {
      handleSave();
    } else if (e.key === 'Escape') {
      setEditText(todo.text);
      setIsEditing(false);
    }
  };

  return (
    <li className="todo-item">
      <input
        type="checkbox"
        className="todo-checkbox"
        checked={todo.completed}
        onChange={() => toggleTodo(todo.id)}
      />
      
      {isEditing ? (
        <input
          ref={editInputRef}
          type="text"
          className="todo-edit-input"
          value={editText}
          onChange={(e) => setEditText(e.target.value)}
          onBlur={handleSave}
          onKeyDown={handleKeyDown}
        />
      ) : (
        <p 
          className={`todo-text ${todo.completed ? 'completed' : ''}`}
          onDoubleClick={handleEdit}
        >
          {todo.text}
        </p>
      )}
      
      <div className="todo-actions">
        {!isEditing && (
          <button 
            className="todo-edit"
            onClick={handleEdit}
            aria-label="编辑"
          >
            ✏️
          </button>
        )}
        <button 
          className="todo-delete"
          onClick={() => deleteTodo(todo.id)}
          aria-label="删除"
        >
          🗑️
        </button>
      </div>
    </li>
  );
}

export default TodoItem; 